// index.js
// import { BTManager } from "../../lib/bluetoothManager"
const {
  handleToast,
  handleAlert,
  closeToast
} = require("../../utils/alertUtil"); /**提示框工具类*/

var JlModel;
const appControlAPI = requirePlugin("hello-plugin")
const app = getApp() // 获取应用实例
Page({
  data: {
    /* 首页右上角连接状态图标 */
    blebuttonText: "off_watch.png",
    /* 是否连接蓝牙设备 */
    isConnectedBluetooth: false,
    // 是否显示杰理OTA模块
    flag: false,
    // 是否是手表
    isWatch: true,
  },
  /** 
   * 生命周期回调—监听页面加载
   * 页面加载时触发。一个页面只会调用一次，可以在 onLoad 的参数中获取打开当前页面路径中的参数。
   */
  onLoad() {
    var that = this;
    appControlAPI.onBLEConnectionStateChange((res) => {
      console.log("监听到蓝牙状态发生改变：", res);
      if (res.connected && !app.globalData.isOTA) {
        const deviceId = wx.getStorageSync('deviceId')
        setTimeout(() => {
          appControlAPI.queryDeviceBasicInfo((state, res) => {
            console.log("设备类型：", res.deviceType);
            app.globalData.deviceInfo = res
          })
          appControlAPI.queryDevcieModel((state, res) => {
            app.globalData.deviceId = deviceId
            app.globalData.BDevName = res
            app.globalData.isConnectedBluetooth = true;
            handleToast("蓝牙已连接,数据加载中", "loading", 3.5)
            const isJL = appControlAPI.isJieLi()
            console.log("当前是否为杰理设备：", isJL);
            that.setData({
              // blebuttonText: "connect.png",
              isWatch: !app.globalData.deviceInfo.deviceType == 1,
              isConnectedBluetooth: true,
              flag: isJL && app.globalData.supportOTA,
            })
            // 判断是否为杰理设备并开启认证初始化
            if (this.data.flag && !app.globalData.isJlAutned) {
              require('../../lib/index', (mod) => {
                JlModel = mod
                console.log("蓝牙是否连接：" + app.globalData.isConnectedBluetooth);
                // 设备已连接，开始认证
                if (app.globalData.isConnectedBluetooth) {
                  console.log("JLmod:" + JlModel);
                  JlModel && JlModel.startJLAuth()
                }
              }, ({
                errMsg,
                mod
              }) => {
                console.error(`path: ${mod}, ${errMsg}`)
              })
            }
            this.onShow()
          });
        }, 2000)

      } else {
        app.globalData.isConnectedBluetooth = false;
        app.globalData.deviceId = ""
        app.globalData.devcieInfo = null
        app.globalData.BDevName = ""
        this.setData({
          isConnectedBluetooth: false,
          blebuttonText: "off_watch.png"
        })
      }
    });

    if (app.globalData.isConnectedBluetooth == true) {

      handleToast("蓝牙已连接,数据加载中", "loading", 3.5)
      const isJL = appControlAPI.isJieLi()
      that.setData({
        // blebuttonText: "connect.png",
        isWatch: !app.globalData.deviceInfo.deviceType == 1,
        isConnectedBluetooth: app.globalData.isConnectedBluetooth,
        flag: isJL && app.globalData.supportOTA,
      })
      // 判断是否为杰理设备并开启认证初始化
      if (this.data.flag && !app.globalData.isJlAutned) {
        require('../../lib/index', (mod) => {
          JlModel = mod
          console.log("蓝牙是否连接：" + app.globalData.isConnectedBluetooth);
          // 设备已连接，开始认证
          if (app.globalData.isConnectedBluetooth) {
            console.log("JLmod:" + JlModel);
            JlModel && JlModel.startJLAuth()
          }
        }, ({
          errMsg,
          mod
        }) => {
          console.error(`path: ${mod}, ${errMsg}`)
        })
      }

    } else {
      // 没有连接蓝牙提示
      handleToast("蓝牙未连接！点击右上角图标即可连接设备", "warning", 3.5)
    }

  },
  onShow() {
    let imgurl = app.globalData.isConnectedBluetooth ? "connect" : "off"
    let deviceType = "watch"
    if (app.globalData.isConnectedBluetooth) {
      deviceType = app.globalData.deviceInfo.deviceType == 1 ? "ring" : "watch"
    }
    this.setData({
      blebuttonText: imgurl + '_' + deviceType + ".png"
    })

  },
  /** 监听页面下滑事件 */
  onPullDownRefresh: function () {},
  /**
   * 点击蓝牙图标跳转至蓝牙列表界面
   */
  clickConnectBle() {
    wx.reLaunch({
      // url: '/pages/cmdView/scan/scan'   // 带表盘功能
      url: '/pages/bleList/bleList' // 不带表盘
    })
  },

  onUnload(){
    closeToast()
  }

})